#include "mydatamodel.h"
#include <QMessageBox>
#include <QDesktopServices>

myDataModel::myDataModel(QObject *parent, QTableView *t,QString q)
    : QSortFilterProxyModel(parent)
{
    table=t;
    sqlModel=new QSqlQueryModel;
    setQuery(q);
    setSourceModel(sqlModel);
    setFilterCaseSensitivity(Qt::CaseInsensitive);
    sort(0);
    table->setModel(this);
}

void myDataModel::setHeader(QStringList header)
{
    for(int i=0;i<header.count();i++)sqlModel->setHeaderData(i, Qt::Horizontal, header.at(i));
}

void myDataModel::setQuery(QString q)
{
    query=q;
    sqlModel->setQuery(q);

}

QString myDataModel::getData(int i)
{
    return data(index(table->currentIndex().row(),i)).toString();

}

void myDataModel::itemAdded()
{
    sqlModel->setQuery(query);
    Qt::SortOrder sOrder=sortOrder();
    int sColumn=sortColumn();
    sort(0);
    table->selectionModel()->setCurrentIndex(index(rowCount()-1,0),QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Rows);
    sort(sColumn,sOrder);
    table->scrollTo(table->currentIndex());

}

void myDataModel::itemChanged()
{
    QModelIndex index=table->currentIndex();
    sqlModel->setQuery(query);
    table->selectionModel()->setCurrentIndex(index,QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Rows);

}


bool myDataModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
    bool result=false;
    for(int i=0;i<sourceModel()->columnCount();i++){
        QModelIndex index = sourceModel()->index(sourceRow, i, sourceParent);
        result=result||(sourceModel()->data(index).toString().contains(filterRegExp()));
    }
    return result;
}
